﻿using MediatR;
using PublicClass;
using S.Organization.Domian.Model;
using S.Organization.Infrastructure;
using S.Organization.Read.API.Application.Command.CottageCommand;

namespace S.Organization.Read.API.Application.CommandHandler.CottageCommandHandler
{
    public class GetCottageCommandHandler : IRequestHandler<GetCottageCommand, PageInfo<CottageSetting>>
    {
        private readonly IBaseRepository<CottageSetting> _repository;


        public GetCottageCommandHandler(IBaseRepository<CottageSetting> repository)
        {
            _repository = repository;
        }

        public async Task<PageInfo<CottageSetting>> Handle(GetCottageCommand request, CancellationToken cancellationToken)
        {
        var query=    await _repository.AllAsync();



            if (!string.IsNullOrEmpty(request.Type))
            {
                query = query.Where(x => x.CottageType == request.Type);
            }

            //数据总条数
            int Total = query.Count();
            //总页数
            int Count = (int)Math.Ceiling(Total * 1.0 / (request.Size));

            if (!string.IsNullOrEmpty(request.Name))
            {
                query = query.Where(x => x.CottageName == request.Name);
            }



            if (!string.IsNullOrEmpty(request.Principal))
            {
                query = query.Where(x => x.Principal == request.Principal);
            }


            query = query.Skip((request.Index - 1) * request.Size).Take(request.Size);



            PageInfo<CottageSetting> list = new PageInfo<CottageSetting>();
            list.totalCount = Total;
            list.pageCount = Count;
            list.datas = query.ToList();
            return list;
        }
    }
}
